﻿using Gnivc.CarDealership.Api.Application.Abstractions.Repositories;
using Gnivc.CarDealership.Api.Domain.Entities;
using Microsoft.AspNetCore.Mvc;

namespace Gnivc.CarDealership.Api.Controllers;

[Route("api/[controller]")]
public class ModelsController : ApiController
{
    private readonly IModelRepository _modelRepository;
    private readonly IBrandRepository _brandRepository;

    public ModelsController(
        IModelRepository modelRepository, 
        IBrandRepository brandRepository)
    {
        _modelRepository = modelRepository;
        _brandRepository = brandRepository;
    }

    [HttpGet("{brandId}")]
    public async Task<IResult> GetModels(Guid brandId)
    {
        var getModelsResult = 
            await _modelRepository.GetAllByBrandAsync(brandId);

        if (getModelsResult.IsError)
            return Problem(getModelsResult.Errors);

        var models = getModelsResult.Value!;

        return Results.Ok(models.Select(x => new 
        { 
            ModelId = x.Id, 
            ModelText = x.Name 
        }));
    }

    [HttpPost("create")]
    public async Task<IResult> CreateModel(
        [FromQuery] Guid brandId,
        [FromQuery] string name)
    {
        var getBrandResult = await _brandRepository.GetByIdAsync(brandId);

        if (getBrandResult.IsError)
            return Problem(getBrandResult.Errors);

        var brand = getBrandResult.Value!;

        var model = new Model(Guid.NewGuid(), name, brand);

        var addResult = await _modelRepository.AddAsync(model);

        if (addResult.IsError)
            return Problem(addResult.Errors);

        return Results.Ok(new
        {
            ModelId = model.Id,
            ModelText = model.Name
        });
    }

    [HttpPatch("update")]
    public async Task<IResult> UpdateModel(
        [FromQuery] Guid id, 
        [FromQuery] string name)
    {
        var getModelResult = await _modelRepository.GetByIdAsync(id);

        if (getModelResult.IsError)
            return Problem(getModelResult.Errors);

        var model = getModelResult.Value!;

        model.Name = name;

        var updateResult = await _modelRepository.UpdateAsync(model);

        if (updateResult.IsError)
            return Problem(updateResult.Errors);

        return Results.Ok();
    }

    [HttpDelete("delete")]
    public async Task<IResult> DeleteModel([FromQuery] Guid id)
    {
        var deleteResult = await _modelRepository.DeleteAsync(id);

        if (deleteResult.IsError)
            return Problem(deleteResult.Errors);

        return Results.Ok();
    }
}